import os

import requests
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QIcon, QFont, QPalette, QBrush, QPixmap, QImage
from PyQt5.QtWidgets import QWidget, QPushButton, QLabel, QHBoxLayout, QVBoxLayout, QApplication
from functools import partial

import global_config
from ui.Logined_in_window import Logined_in_window
from ui_rqh.FunctionPageParts import FunctionPage
from window.My_change_password_window import My_change_password_window
from window.My_set_forget_password_question_window import My_set_forget_password_question_window
from window.My_sponsor import My_sponsor


class My_logined_in_window(QWidget, Logined_in_window):
    # 自定义信号
    close_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # rqh的功能界面
        self.function_page = FunctionPage()
        self.function_page.resize(900, 700)

        palette = QPalette()
        # 设置密保问题界面
        self.security_question_page = My_set_forget_password_question_window()

        # sponsor界面
        self.sponsor_page = My_sponsor()

        # 设置窗口标题等
        base_path = os.path.dirname(__file__)
        base_path = base_path.replace('\\window', '')
        icon_path = os.path.join(base_path, 'icon')
        icon_path = os.path.join(icon_path, 'Python.png')
        self.setWindowTitle('欢迎登录')
        icon = QIcon(icon_path)
        self.setWindowIcon(icon)
        self.function_page.setWindowIcon(icon)
        self.sponsor_page.setWindowIcon(icon)
        self.security_question_page.setWindowIcon(icon)

        self.container = QVBoxLayout()

        # 设置背景图片
        back_path = os.path.join(base_path, 'background')
        back_path = os.path.join(back_path, 'background.jpg')
        palette.setBrush(QPalette.Background, QBrush(QPixmap(back_path)))
        self.setPalette(palette)

        # 让Qlabel中加载一张图片
        self.sponsor_page.resize(200, 400)
        self.sponsor_page.setWindowTitle('感谢支持')
        picture_path = os.path.join(base_path, 'pictures')
        picture_path = os.path.join(picture_path, 'sponsor.jpg')
        picture_path = picture_path.replace('\\', '/')
        style = "QLabel{\nborder-image:url(" + picture_path + ") 4 4 4 4 stretch stretch;\n}"
        self.sponsor_page.label.setStyleSheet(style)

        self.username = ''
        self.password = ''
        self.login_time = ''
        self.ids = []
        # 修改密码时弹出的窗口
        self.change_password_window = My_change_password_window()

        # 修改密码按钮
        self.change_password_button_in_setting.clicked.connect(self.switch_to_change_password_window)
        # 当修改密码窗口点击确认修改按钮之后会面临登出的自动操作
        self.change_password_window.confirm_button.clicked.connect(self.attempt_to_close_this_window)
        # 当点击功能界面的开始查重按钮时弹出查重界面
        self.function_button.clicked.connect(self.pop_up_function_page)

        # 赞助按钮
        self.sponsor_button.clicked.connect(self.pop_up_sponsor_page)

        # 退出登录按钮
        self.quit_login_button_in_setting.clicked.connect(self.quit)

        # 设置密保问题的按钮
        self.security_button.clicked.connect(self.pop_up_security_question_page)

        self.refresh_button.clicked.connect(self.refresh)

    def refresh(self):
        self.clear_history()
        self.load_history_page()

    def clear_history(self):
        while self.container.count():
            child = self.container.takeAt(0)
            print(child)
            if child.widget():
                child.widget().deleteLater()
        self.scrollAreaWidgetContents.resize(900, 700)

    def set_username(self, username):
        self.username = username
        self.username_text_in_setting.setText(username)
        self.function_page.setUsername(username)
        self.security_question_page.set_username(username)

    def set_password(self, password):
        self.password = password

    def set_login_time(self, login_time):
        self.login_time = login_time
        self.login_time_text_in_setting.setText(login_time)

    def switch_to_change_password_window(self):
        self.change_password_window.show()
        self.change_password_window.set_username(self.username)
        self.change_password_window.set_password(self.password)

    def pop_up_function_page(self):
        self.function_page.show()

    def pop_up_sponsor_page(self):
        self.sponsor_page.show()

    def pop_up_security_question_page(self):
        self.security_question_page.show()

    # 如果密码修改成功后，要实现登出操作
    def attempt_to_close_this_window(self):
        if self.password != self.change_password_window.password:
            self.close()
            self.close_signal.emit('')

    # 登出操作
    def quit(self):
        self.close()
        self.close_signal.emit('')

    # 加载历史纪录页面
    def load_history_page(self):
        url = 'http://' + global_config.localhost + ':8000/getRecords/'
        params = {
            'username': self.username
        }
        result = requests.get(url, params=params).json()

        for i in range(len(result['result'])):
            id = str(result['result'][i]['id'])
            date = str(result['result'][i]['date'])
            label = 'id:' + id + '    ' + date
            btn = QPushButton(label, self.scrollAreaWidgetContents)
            btn.setFont(QFont('AgencyFB', 20))
            btn.clicked.connect(partial(self.load_full_history, id))
            # h_layout = QHBoxLayout()
            # h_layout.addWidget(btn)
            self.scrollAreaWidgetContents.resize(self.scrollAreaWidgetContents.width(),
                                                 self.scrollAreaWidgetContents.height() + 50)
            # self.container.addLayout(h_layout)
            self.container.addWidget(btn)
        self.scrollAreaWidgetContents.setLayout(self.container)

        # 设置历史记录区域的背景
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(QPixmap('./background/background.jpg')))
        self.scrollAreaWidgetContents.setPalette(palette)

    # 加载一个完整的历史纪录
    def load_full_history(self, id):
        url = 'http://' + global_config.localhost + ':8000/load/'
        params = {
            'id': int(id)
        }
        response = requests.get(url, params=params)
        if response.status_code == 200:
            zip_filename = 'history.zip'
            save_path = './' + zip_filename
            with open(save_path, 'wb') as file:
                file.write(response.content)
        self.function_page.fileToResult('./history.zip')

    def closeEvent(self, event):
        self.function_page.close()
        self.change_password_window.close()
        self.sponsor_page.close()
        self.security_question_page.close()
        self.security_question_page.pop_up_success.close()
        self.clear_history()
        # 向后端发送登出请求
        url = 'http://' + global_config.localhost + ':8000/logout/'
        params = {
            'username': self.username
        }
        result = requests.get(url, params=params).json()
        if result['result'] == 'success':
            event.accept()
        else:
            event.ignore()
